package com.mioto.ld.module.file.controller;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import com.mioto.ld.exception.BasicException;
import com.mioto.ld.module.file.FileHelper;
import com.mioto.ld.module.file.model.FileInfo;
import com.mioto.ld.module.file.service.FileService;
import com.mioto.ld.result.ResultData;
import com.mioto.ld.result.SystemTip;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author mioto-qinxj
 * @date 2024/5/14
 * @desc
 */
@RestController
@RequestMapping("file")
@Api(tags = "文件管理")
public class FileController {

    @Resource
    private FileHelper fileHelper;
    @Resource
    private FileService fileService;

    @PostMapping("/upload")
    @ApiOperation(value="文件上传")
    public synchronized ResultData upload (@RequestPart("files") MultipartFile[] files){
        List<FileInfo> fileInfos;
        try {
            fileInfos = new ArrayList<>(files.length);
            for (MultipartFile file : files) {
                //文件存储路径+文件名
                String realPath = StrBuilder.create()
                        .append(fileHelper.createDirPath())
                        .append(StrUtil.SLASH)
                        .append(fileHelper.createNewFileName(file.getOriginalFilename()))
                        .toString();
                file.transferTo(new File(realPath));
                fileInfos.add(fileHelper.buildFileInfo(realPath,file.getOriginalFilename()));
            }
            fileService.batchInsert(fileInfos);
        }catch (Exception exception){
            return ResultData.result(SystemTip.FILE_UPLOAD_FAIL);
        }
        return ResultData.success(fileInfos);
    }

    /**
     * 文件下载
     */
    @GetMapping("/download/{id}")
    @ApiOperation(value="文件下载")
    public void download (@PathVariable("id") String id, HttpServletResponse response){
        FileInfo fileInfo = fileService.findFileInfo(id);
        Optional.ofNullable(fileInfo).orElseThrow(() -> new BasicException(SystemTip.FILE_NOT_EXIST));
        fileHelper.download(response,fileInfo);
    }

}
